import axios from "axios";
import router from "@/router";

import { getToken } from "./auto";
import { Message } from "element-ui";

import errorHandler from "@/utils/errHandler";
// axios拦截处理s

axios.interceptors.request.use(
  (config) => {
    // 在发送请求之前做些什么
    const token = getToken();
    if (token) {
      config.headers["authorization"] = token;
    }
    // 允许携带cookie
    // config.withCredentials = true;
    return config;
  },
  (error) => {
    // 对请求错误做些什么
    console.log(error);
    return Promise.reject(error);
  }
);
const types = [
  // 各种特殊类型请求头
  "appcation/octet-stream",
];

axios.interceptors.response.use(
  (response) => {
    const res = response.data;
    if (response.headers && response.headers["content-type"]) {
      for (var i = 0; i < types.length; i++) {
        // 特殊响应头
        if (response.headers["content-type"].includes(types[i])) {
          return res;
        }
      }
    }

    if (res.code !== 20000) {
      Message({
        message: res.message || "Error",
        type: "error",
        duration: 5 * 1000,
      });
      if (
        res.code === 50008 ||
        res.code === 50012 ||
        res.code === 50014 ||
        res.code === 50017
      ) {
        router.push({ name: "login" }, () => {});
      }
      return Promise.reject(new Error(res.message || "Error"));
    } else {
      return res;
    }
  },
  (err) => {
    const { data } = err.response;
    // 如果有data数据,则显示data中的错误信息
    data.isAxiosError = true;
    errorHandler(data);
    if (data.code) {
      Message({
        message: data.message,
        type: "error",
        duration: 5 * 1000,
      });
      if (data.code === 50027) {
        router.push({ name: "401" }, () => {});
      }
    } else {
      Message({
        message: err.message,
        type: "error",
        duration: 5 * 1000,
      });
    }
    return Promise.reject(err);
  }
);

export default axios;
